﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Toetoe.Infrastructure;
using Toetoe.Models.DAL;
using Toetoe.Models.Domain;

namespace Toetoe.Controllers
{
    public class TittieController : Controller
    {
        private BerichtRepository _berichtRepository;

        public TittieController(BerichtRepository berichtRepository)
        {
            this._berichtRepository = berichtRepository;
        }

        public TittieController() : this(new BerichtRepository(ObjectContextPerHttpRequest.Context))
        {
        }

        //
        // GET: /Tittie/

        public ActionResult Index()
        {
            if (Request.IsAjaxRequest())
                return View("BerichtenLijst", _berichtRepository.FindAll());
            return View(_berichtRepository.FindAll());
        }


        //
        // POST: /Tittie/Create

        [HttpPost]
        public ActionResult Create(FormCollection formValues)
        {
            try
            {
                Bericht bericht = BerichtFactory.MaakBericht(formValues["Gebruikersnaam"], formValues["Titel"],
                                                             formValues["Inhoud"]);

                _berichtRepository.Add(bericht);
                _berichtRepository.SaveChanges();
                return RedirectToAction("Index");
            }
            catch(ArgumentException e)
            {
                TempData["error"] = e.Message;
                return RedirectToAction("Index");
            }
        }
        
        //
        // GET: /Tittie/Edit/5
 
        public ActionResult Edit(int id)
        {
            var bericht = _berichtRepository.FindById(id);
            return View(bericht);
        }

        //
        // POST: /Tittie/Edit/5

        [HttpPost]
        public ActionResult Edit(int id, FormCollection collection)
        {
            var bericht = _berichtRepository.FindById(id);
            UpdateModel(bericht, collection.ToValueProvider());
            _berichtRepository.SaveChanges();
            return RedirectToAction("Index");
        }

        //
        // GET: /Tittie/Delete/5
 
        public ActionResult Delete(int id)
        {
            return View(_berichtRepository.FindById(id));
        }

        //
        // POST: /Tittie/Delete/5

        [HttpPost]
        public ActionResult Delete(int id, FormCollection collection)
        {
            try
            {
                Bericht bericht = _berichtRepository.FindById(id);
                _berichtRepository.Delete(bericht);
                _berichtRepository.SaveChanges();
                return RedirectToAction("Index");
            }
            catch
            {
                return RedirectToAction("Index");
            }
        }
    }
}
